<?php

namespace app\api\controller\xykeep;
use addons\xykeep\exception\Exception;
use app\api\model\xykeep\Config;
use addons\xykeep\library\Decrypt\weixin\wxBizDataCrypt;
use app\common\controller\Api;
use app\api\model\xykeep\Take as TakeModel;
use app\api\model\xykeep\User as UserModel;
use app\common\library\Sms;
use app\common\model\Card as CardModel;
use app\common\model\UserCard as UserCardModel;
use think\Db;
use think\Validate;
use fast\Random;
use fast\Http;

/**
 * XYkeep会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['phone','login','wechat','smslogin','h5wechat'];
    protected $noNeedRight = ['*'];
    
    public function _initialize()
    {
        parent::_initialize();
		$this->auth->setAllowFields(['id','username','nickname','mobile','avatar',
			'xykeep_bind_share','xykeep_consume','is_supplier',
			'gender','money','successions','maxsuccessions','prevtime','logintime','loginip','jointime']);
    }

	/**
     * 登录
     */
    public function login()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$account = $this->request->post('mobile');
			$password = $this->request->post('password');
			if (!$account || !$password) {
				$this->error(__('Invalid parameters'));
			}
			$ret = $this->auth->login($account, $password);
			if ($ret) {
				$this->success(__('Logged in successful'), self::userInfo());
			} else {
				$this->error($this->auth->getError());
			}
		}
		$this->error(__('非法请求'));
    }

	/**
     * 退出登录
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

	/**
     * 手机验证码登录
     */
    public function smslogin()
    {
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$mobile = $this->request->post('mobile');
			$captcha = $this->request->post('captcha');
			if (!$mobile || !$captcha) {
				$this->error(__('参数错误'));
			}
			if (!Validate::regex($mobile, "^1\d{10}$")) {
				$this->error(__('手机号错误'));
			}
//			if (!Sms::check($mobile, $captcha, 'register')) {
//				$this->error(__('验证码错误'));
//			}
			$user = \app\common\model\User::getByMobile($mobile);
			$isInfo = 0;
			if ($user) {
				if ($user->status != 'normal') {
					$this->error(__('账号已禁用'));
				}
				$isInfo = 2;
				$ret = $this->auth->direct($user->id);
			} else {
				$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
				$this->auth->register('U'.Random::alnum(6), Random::alnum(), '', $mobile, [
					'nickname' => 'U-'.Random::nozero(6), 
					'avatar' => Config::getValueByName('xykeep')['useravatar']?Config::getValueByName('xykeep')['useravatar']:''
				]);
				$isInfo = 1;
			}
			if ($ret) {
				Sms::flush($mobile, 'mobilelogin');
				$this->success(__('登录成功'), self::userInfo($isInfo));
			} else {
				$this->error($this->auth->getError());
			}
		}
		$this->error(__('非法请求'));
    }

	/**
     * 公众号微信授权登录
     */
    public function h5wechat()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$post = $this->request->post();
			$platform = request()->header('platform');
		   
		    // 获取配置
		    $config = Config::getValueByName('wxOfficialAccount');

			if(empty($config['app_id']) || empty($config['secret'])){
				$this->error(__('请到后台配置中心平台配置中配置微信公众号AppID和AppSecret'));
			}

	        $params = [
			    'appid'    => $config['app_id'],
			    'secret'   => $config['secret'],
			    'code'       => $post['code'],
				'grant_type' => 'authorization_code'
			];
			
			$ret = \think\Db::transaction(function () use ($params,$platform) {
				try {
					
					$result = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
					if ($result['ret']) {
						$access = (array)json_decode($result['msg'], true);

						//var_dump($access);

						//获取用户信息
						$queryArr = [
							"access_token" => $access['access_token'],
							"openid"       => $access['openid']
						];
						$ret = Http::sendRequest("https://api.weixin.qq.com/sns/userinfo", $queryArr, 'GET');
						if ($ret['ret']) {
							$json = (array)json_decode($ret['msg'], true);
							$third = model('app\api\model\xykeep\Third')->get(['platform' => $platform, 'openid' => $json['openid']]);
							if ($third && $third['user_id'] != 0) {
							    $third->save([
									'openid' => $json['openid'],
							        'logintime' => time(),
							    ]);
							    $ret = $this->auth->direct($third['user_id']);
							    
							} else {
							   

							    $nickname = $json['nickname'];
							    $avatar = $json['headimgurl'];
								
								// 注册账户
								$this->auth->register('U'.Random::alnum(6), Random::alnum(), '', '', [
									'nickname' => $nickname, 
									'avatar' => $avatar
								]);
								
								// 新增$third
								$third = model('app\api\model\xykeep\Third');
							    $third->platform  = $platform;
								$third->openid  = $json['openid'];
							    $third->logintime  = time();
							    $third->user_id  = $this->auth->id;
							    $third->save();
							}
							return true;
						}else{
							$this->error('获取用户信息失败！'); 
						}
					}else{
						$this->error('获取openid失败！'); 
					}
					return true;
				} catch (\Exception $e) {
					$this->error($e->getMessage());
				}
				return true;
			});	
			
		    if ($ret) {
    			$this->success(__('Logged in successful'), self::userInfo());
    		} else {
    			$this->error($this->auth->getError());
    		}
		}
		$this->error(__('非法请求'));
    }


	/**
     * 小程序微信授权登录
     */
    public function wechat()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$post = $this->request->post();
			$platform = request()->header('platform');
		   
		    // 获取配置
		    $config = Config::getValueByName('wxminiprogram');

			if(empty($config['app_id']) || empty($config['secret'])){
				$this->error(__('请到后台配置中心平台配置中配置微信小程序AppID和AppSecret'));
			}

	        $params = [
			    'appid'    => $config['app_id'],
			    'secret'   => $config['secret'],
			    'js_code'  => $post['code'],
			    'grant_type' => 'authorization_code'
			    ];
			
			$ret = \think\Db::transaction(function () use ($params,$platform) {
				$isInfo = 0;
				try {
					
					$result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
					$json = (array)json_decode($result['msg'], true);
					
					// 判断third是否存在,存在快速登录
					$third = model('app\api\model\xykeep\Third')->get(['platform' => $platform, 'openid' => $json['openid']]);
					
					if ($third && $third['user_id'] != 0) {
						//如果已经有账号则直接登录
						$isInfo = 2;
						$third->save([
							'openid' => $json['openid'],
							'logintime' => time(),
						]);
						$this->auth->direct($third['user_id']);
					} else {
					
						// 开始登录
						$isInfo = 1;
						$this->auth->register('U'.Random::alnum(6), Random::alnum(), '', '', [
							'nickname' => 'U-'.Random::nozero(6), 
							'avatar' => Config::getValueByName('xykeep')['useravatar']?Config::getValueByName('xykeep')['useravatar']:''
						]);

						// 新增$third
						$third = model('app\api\model\xykeep\Third');
						$third->platform  = $platform;
						$third->openid  = $json['openid'];
						$third->session_key  = $json['session_key'];
						$third->logintime  = time();
						$third->user_id  = $this->auth->id;
						$third->save();
						
					}
					return $isInfo;
				} catch (\Exception $e) {
					$this->error($e->getMessage());
				}
				return $isInfo;
			});	
			
		    if ($ret) {
    			$this->success(__('Logged in successful'), self::userInfo($ret));
    		} else {
    			$this->error($this->auth->getError());
    		}
		}
		$this->error(__('非法请求'));
    }
    
    /**
     * 手机号授权登录
     */
    public function phone()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$post = $this->request->post();
			$platform = request()->header('platform');
		    if (!isset($post['iv'])) {
		        $this->error(__('获取手机号异常'));
		    }
		    // 获取配置
		    $config = Config::getValueByName('wxminiprogram');

		    // 微信小程序一键登录
	        $params = [
			    'appid'    => 'wxb6a90f5de8fb178f',
			    'secret'   => '0bbbf5deb2fea4584e3b93df2697d3d9',
			    'js_code'  => $post['code'],
			    'grant_type' => 'authorization_code'
			    ];
			
			$ret = \think\Db::transaction(function () use ($params,$platform,$post) {
				$isInfo = 0;
				try {
					
					$result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
					$json = (array)json_decode($result['msg'], true);

					// 判断third是否存在,存在快速登录
					$third = model('app\api\model\xykeep\Third')->get(['platform' => $platform, 'openid' => $json['openid']]);
					
					if ($third && $third['user_id'] != 0) {
						//如果已经有账号则直接登录
						$isInfo = 2;
						$third->save([

							'openid' => $json['openid'],
							'logintime' => time(),
						]);
						$this->auth->direct($third['user_id']);
					} else {

						// 手机号解码
						$decrypt = new wxBizDataCrypt($params['appid'], $json['session_key']);
						$decrypt->decryptData($post['encryptedData'], $post['iv'], $data);
						$data = (array)json_decode($data, true);
						// 开始登录
						$mobile = $data['phoneNumber'];
                        // 这行代码会产生一种现象，用A微信号绑定某号码，如果在微信中用B微信号绑定该号码，则A和B同时可以进行登录
						$user = \app\common\model\User::getByMobile($mobile);
						if ($user) {
							if ($user->status !== 'normal') {
                                throw new \Exception("账号被禁止登录");
							}
							//如果已经有账号则直接登录
							$isInfo = 2;
							$this->auth->direct($user->id);
						} else {
							$isInfo = 1;
							$this->auth->register('U'.Random::alnum(6), Random::alnum(), '', $mobile, [
								'nickname' => 'U-'.Random::nozero(6), 
								'avatar' => Config::getValueByName('xykeep')['useravatar']?Config::getValueByName('xykeep')['useravatar']:''
							]);
						}

						// 新增$third
						$third = model('app\api\model\xykeep\Third');
						$third->platform  = $platform;
						$third->openid  = $json['openid'];
						$third->session_key  = $json['session_key'];
						$third->logintime  = time();
						$third->user_id  = $this->auth->id;
						$third->save();
						
					}
					return $isInfo;
				} catch (\Exception $e) {
					$this->error($e->getMessage());
				}
				return $isInfo;
			});	
			
		    if ($ret) {
    			$this->success(__('Logged in successful'), self::userInfo($ret));
    		} else {
    			$this->error($this->auth->getError());
    		}
		}
		$this->error(__('非法请求'));
    }

	/**
	 * 刷新用户信息
	 */
	public function refresh()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$this->success(__('刷新成功'), self::userInfo());
		}
		$this->error(__('非法请求'));
	}

	/**
     * 修改信息
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar');
		$mobile = $this->request->post('mobile');
        $gender = $this->request->post('gender');
		
		if(!empty($mobile) && $mobile != $user['mobile']){
			$userE = UserModel::where(['mobile'=>$mobile])->find();
			if(!empty($userE)){
				$this->error(__('手机号已存在'));
			}
			$user->mobile = $mobile;
		}

        $user->gender = $gender;
        $user->nickname = $nickname;
		
        if (!empty($avatar)) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success('修改成功',self::userInfo());
    }


    /**
     * 用户中心
     */
    public function user_center(){
        $user_id = $this->auth->id;

        $userInfo = UserModel::where(['id'=>$user_id])->field($this->auth->getAllowFields())->find();

        //自提点
        $take = TakeModel::where(['user_id'=>$user_id])->find();
        $userInfo['is_take'] = $take ? 1 : 0;

        //最好等级的权益卡
        $top_card_id = UserCardModel::where([
            'card_id' => ['elt',3],
            'user_id' => $user_id
        ])->order('card_id desc')->value('card_id');
        $userInfo['top_card'] = '';
        if($top_card_id){
            $userInfo['top_card'] = CardModel::where(['id'=>$top_card_id])->find();
        }

        $this->success('用户信息',$userInfo);
    }

	/**
	 * 登录后返回用户信息
	 */
	private function userInfo($isInfo = 0)
	{
		// 获取配置
		//$basic = Config::getValueByName('xykeep');
		$userInfo = $this->auth->getUserinfo();

		$userInfo['avatar'] = (strstr($userInfo['avatar'], 'data:image/svg+xml') || empty($userInfo['avatar']))? '/assets/addons/xykeep/imgs/avatar.png' : cdnurl($userInfo['avatar'],true);
	    
		$userInfo['is_info'] = $isInfo;


		$this->success('用户信息',[
			'userInfo' => $userInfo,
		]);

	}
	
}